package com.pb.camera;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.pb.camera.application.App;
import com.pb.camera.helper.JsonHelper;
import com.pb.camera.utils.Constants;
import com.pb.camera.utils.Encryption;
import com.pb.camera.utils.JsonAnalyle;
import com.pb.camera.utils.MyTextWatcher;
import com.pb.camera.utils.uniqueID;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class WeiXinBindActivity  extends Activity  implements OnClickListener{
private EditText  edit_accout;
private EditText  edit_password;
private EditText  edit_email;
private LinearLayout linear_bind;
private  LinearLayout linear_root;
private ImageView  image_account_reset;
private  ImageView  image_password;
private  ImageView  image_back;
private String openId;
private   boolean canBind=false;
private   String gesture="";
private String userId;	
private Handler  handler=new Handler(){
	public void handleMessage(Message msg) {
		
		if(msg.arg2==6)
		{
			 Toast.makeText(WeiXinBindActivity.this,(String) msg.obj, Toast.LENGTH_SHORT).show();;
			
		}else  if (msg.what==110) {
			   //绑定微信
			  getCode(Constants.BindWeiXin(edit_accout.getText().toString(),urlEncode(openId), "1"), WeiXinBindActivity.this, 0);
		}
	}
};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		   requestWindowFeature(Window.FEATURE_NO_TITLE); 
		setContentView(R.layout.weixin_bind);
		  if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
	            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
	            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
	        }
		App.getInstance().getAllActivity().add(this);
		  initView();
		  
		
	}	
	private void initView()
	{

		image_back=(ImageView) findViewById(R.id.weixin_bind_image_back);
		image_back.setOnClickListener(this);
	    openId=getIntent().getExtras().getString("openId");		
		edit_accout=(EditText) findViewById(R.id.weiixin_bind_edit_account);
		edit_password=(EditText) findViewById(R.id.weiixin_bind_edit_password);
		linear_bind=(LinearLayout) findViewById(R.id.weiixin_bind_line_bind);
		linear_bind.setOnClickListener(this);
		linear_root=(LinearLayout) findViewById(R.id.weiixin_bind_linear_rootview);
		linear_root.setOnClickListener(this);
		image_account_reset=(ImageView) findViewById(R.id.weiixin_bind_image_reset_phonenum);
		image_password=(ImageView) findViewById(R.id.weiixin_bind_image_reset_code);
		edit_accout.addTextChangedListener(new MyTextWatcher(edit_accout, image_account_reset));
		edit_password.addTextChangedListener(new MyTextWatcher(edit_password ,image_password));
		
	}
	
	
	private   void   weiixin_bind()
	{
		//绑定之前先验证账号是否是已经注册的账号或者该账号已经绑定别的微信号码
		//使用的接口是正常登陆的接口
		//返回50015 代表微信号绑定到别的账号了
		getCode(Constants.login(edit_accout.getText().toString(),urlEncode(Encryption.encode(edit_password.getText().toString())),uniqueID.id(this), urlEncode(openId)), this,1);		
		  //getCode(Constants.BindWeiXin(edit_accout.getText().toString(),urlEncode(openId), "1"), this, 0);
	}
	
	   private void   getCode(String  url,final Activity  activity,final int mode)
		  {
			   HttpUtils httpUtils = new HttpUtils();
			   RequestParams params=new RequestParams();
				httpUtils.send(HttpMethod.POST, url,  new RequestCallBack<String>() {
					@Override
					public void onFailure(HttpException arg0, String arg1) {
						
						Toast.makeText(activity, "网络访问失败,请检查你的网络", 0).show();
                           finish();
					}
					@Override
					public void onSuccess(ResponseInfo<String> arg0) {								
				    boolean flag=  JsonAnalyle.jsonAnalyse(arg0.result, WeiXinBindActivity.this, null,handler);	
				    Log.i("123", "微信绑定账号的结果"+arg0.result);
						if (mode==1)
						{    //判断账号是否可以用来绑定
							//使用的是正常登陆的接口
							//若是登录成功可以绑定
							//然后获取手势,判断是否为空
							if(flag)
							{		
							   handler.sendEmptyMessage(110);
							   Map  map=JsonAnalyle.logSuccess(arg0.result);		
							   //但是gesture 
							   saveUserMessage(edit_accout.getText().toString(), edit_password.getText().toString(),
									(String) map.get("gesture"), (String) map.get("userid"), (String) map.get("email"),(String) map.get("mobile"), (String) map.get("openid"));
							   updateAppUserInfo(edit_accout.getText().toString(), edit_password.getText().toString(),
							   (String) map.get("gesture"),(String) map.get("userid"),(String) map.get("email"), (String) map.get("mobile"),  (String) map.get("openid"));							 
							   gesture=(String)map.get("gesture");
							   userId=(String)map.get("userid");	
							 
							}											   
						}
						else if (mode==0)
						{ //微信绑定
							if(flag)
							{//绑定成功的时候
							//需要判断是否已经设置了手势若是没有需要开启手势注册界面
								//手势是空的时候
								if (gesture==null||gesture.equals("")||gesture.equals("default"))
								{   //没有设置手势的时候
									//开启设置手势
									Bundle  bundle =new Bundle();
									bundle.putString("whereFrom", "only_register_gesture");
									bundle.putString("userId", userId);
									Intent intent=new Intent(WeiXinBindActivity.this,CreateGesturePasswordActivity.class);
									startActivity(intent);										
								}
								else 
								{
								//若是设置了手势的时候直接开启首页面吗
									Intent intent = new Intent(WeiXinBindActivity.this,HomePageActivity.class);
								   startActivity(intent);

								}
								//r若是绑定失败 就是flag=false 的时候没有处理呢
							}										
						}
					}				
				});			
		  }
	   
	   private  void  updateAppUserInfo(String account,String password,String   gesture,String userId,String email,String mobile ,String openId)
		  {
			  App application=App.getInstance();
			  application.setAccount(account);
			  application.setOpenId(openId);
			  application.setPassword(urlEncode(password));
			  application.setGesture(gesture);
			  application.setMobile(mobile);
			  application.setEmail(email);
			  application.setUserId(userId);	  
		  }
		  
		  
		  private  void  saveUserMessage(String account,String password,String   gesture,String userId,String email,String mobile ,String openId)
		  {		  
			  SharedPreferences  pre=getSharedPreferences("itisforlife",Context.MODE_PRIVATE);		    		  
		        Editor  editor=pre.edit();
		        editor.putString("account",account);
		        //密码不在返回之内列
		        //自己补充的
		        editor.putString("password",urlEncode(password));	
		        editor.putString("gesture",gesture);
		        editor.putString("openid",openId);	
		        editor.putString("email",email);	
		        editor.putString("userid",userId);	
		        editor.putString("mobile",mobile);
		        editor.commit();		  
		        
		  }
		  
		  
		  
		  private   String   urlEncode(String data)
		  {
			  String   outcome=null;
			  try {
	    outcome=URLEncoder.encode(data, "utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				Log.i("===", "编码错误");
				e.printStackTrace();
			}
			  return  outcome;	  
		  }
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case  R.id.weiixin_bind_linear_rootview:			
				  InputMethodManager imm = (InputMethodManager)
				  getSystemService(Context.INPUT_METHOD_SERVICE);
				  imm.hideSoftInputFromWindow(view.getWindowToken(), 0);     
				break;
			case R.id.weixin_bind_image_back:			
				finish();
				break;
			case R.id.weiixin_bind_line_bind:	
				  weiixin_bind();
				break;
			default:
				break;
			}		
			
		}
		
		@Override
		public void finish() {
			App.getInstance().getAllActivity().remove(this);
			super.finish();
		}
		@Override
		protected void onDestroy() {
			App.getInstance().getAllActivity().remove(this);
			super.onDestroy();
		} 
}
